package com.cdxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdxy.dmr.dataObject.HotSearchDO;
import com.cdxy.dmr.repository.HotSearchRepository;
import com.cdxy.dmr.repository.HotelRepository;
import com.cdxy.dmr.repository.SceneRepository;
import com.cdxy.model.dto.base.resp.BasePageResp;
import com.cdxy.model.dto.req.SearchResultReq;
import com.cdxy.model.dto.resp.SearchResultResp;
import com.cdxy.service.IHotSearchService;
import com.cdxy.util.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 热门搜索 服务实现类
 * </p>
 *
 * @author autoGenCode
 * @since 2020-03-05
 */
@Service
public class HotSearchServiceImpl implements IHotSearchService {

    @Autowired
    private HotelRepository hotelRepository;

    @Autowired
    private SceneRepository sceneRepository;

    @Autowired
    private HotSearchRepository hotSearchRepository;

    @Override
    public BasePageResp<SearchResultResp> searchResult(SearchResultReq searchResultReq) {
        String content = searchResultReq.getContent();

        LambdaQueryWrapper<HotSearchDO> lambdaQueryWrapper = (new QueryWrapper<HotSearchDO>()).lambda();
        IPage<HotSearchDO> hotelDOIPage = new Page<>(0, 10);
        lambdaQueryWrapper.eq(HotSearchDO::getName, content);
        hotelDOIPage = hotSearchRepository.page(hotelDOIPage, lambdaQueryWrapper);

        BasePageResp<SearchResultResp> basePageResp = BeanUtil.copyPropertiesByFastJson(hotelDOIPage, BasePageResp.class);
        List<SearchResultResp> searchResultRespList = BeanUtil.copyPropertiesByFastJson(hotelDOIPage.getRecords(), SearchResultResp.class);
        basePageResp.setRecords(searchResultRespList);
        basePageResp.setLastPage(false);

        return basePageResp;
    }

    @Override
    public boolean searchOnce(String name) {
        if (StringUtils.isBlank(name)) {
            return true;
        }
        HotSearchDO hotSearchDO = hotSearchRepository.getByName(name);
        if (hotSearchDO == null) {
            hotSearchDO = new HotSearchDO();
            hotSearchDO.setName(name);
            hotSearchDO.setCount(1);
            return hotSearchRepository.save(hotSearchDO);
        } else {
            return hotSearchRepository.updateSearchCount(name);
        }
    }
}
